﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MarketDashboardModule.Helpers;
using System.Collections.ObjectModel;
using MarketDashboardModule.Models;
using System.ComponentModel;
using System.Windows.Threading;
using System.Threading;

namespace MarketDashboardModule.ViewModels
{
    public class MyViewModel : INotifyPropertyChanged
    {
        public MyViewModel()
        {
            StockSymbolLoader loader = new StockSymbolLoader();
            loader.Load((bln) =>
            {
                if (bln)
                {
                    Dispatcher.CurrentDispatcher.BeginInvoke((ThreadStart)delegate { AsyncTest(); }, DispatcherPriority.Normal);                    
                }
            });
        }

        private void AsyncTest()
        {
            this.Stocks = Global.Stocks.Take(50).ToObservableCollection();
            FireProperty("Stocks");
        }

        private ObservableCollection<Stock> _stocks = new ObservableCollection<Stock>();
        public ObservableCollection<Stock> Stocks
        {
            get { return _stocks; }
            set { _stocks = value; ; FireProperty("Stocks"); }
        }


        public void RefreshData(string searchText)
        {
            if (searchText.Trim().Length > 0)
            {
                var query = from p in this.Stocks
                            where p.Name.Contains(searchText) ||
                            p.Symbol.Contains(searchText)
                            select p;

                this.Stocks = query.ToObservableCollection();
            }
            else
            {
                this.Stocks = Global.Stocks.ToObservableCollection();
            }
        }



        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void FireProperty(string propName)
        {
            if (null != PropertyChanged)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        #endregion
    }
}